<template>
    <el-form ref="formRef" :rules="rules" :model="formData" label-width="120px">
        <!-- 公告配置 -->
        <el-card shadow="never" class="!border-none mt-4">
            <div class="text-xl font-medium mb-[20px]">公告设置</div>
            <el-form-item label="功能开关" prop="is_open">
                <div class="w-[500px]">
                    <el-switch
                        :active-value="1"
                        :inactive-value="0"
                        v-model="formData.is_open"
                    />
                    <div class="form-tips">开启后用户每天首次进入站点会触发弹框</div>
                </div>
            </el-form-item>
            <el-form-item label="公告标题" prop="title">
                <div class="w-[500px]">
                    <el-input
                        v-model.trim="formData.title"
                        show-word-limit
                    />
                </div>
            </el-form-item>
            <el-form-item label="公告内容" prop="content">
                <div class="w-[500px]">
                    <rich-text v-model="formData.content" :height="600"  />
                </div>
            </el-form-item>
        </el-card>

        <!-- 保存按钮 -->
        <el-card shadow="never" class="!border-none mt-4">
            <el-button
                v-perms="['setting:bulletin:save']"
                :loading="loading"
                type="primary"
                @click="handleSubmit"
            >保存配置</el-button>
        </el-card>
    </el-form>
</template>

<script setup lang="ts">
import feedback from '@/utils/feedback'
import bulletinApi from '@/api/setting/bulletin'

const loading = ref(false)
const formRef = ref()
const formData = reactive({
    is_open: 0,
    title: '',
    content: ''
})

// 表单验证
const rules = {
    'is_open': [
        { required: true, message: '请设置功能状态', trigger: 'blur' }
    ],
    'title': [
        { max: 20, message: '公告标题不能超出20个字符', trigger: ['blur'] },
    ]
}

/**
 * 查询配置参数
 */
const queryConfigs = async (): Promise<void> => {
    const data = await bulletinApi.detail()
    Object.assign(formData, data)
}

/**
 * 提交修改参数
 */
const handleSubmit = async (): Promise<void> => {
    await formRef.value?.validate()

    loading.value = true
    await bulletinApi.save(formData)
        .finally(() => {
            setTimeout(() => {
                loading.value = false
            }, 500)
        })

    await queryConfigs()
    feedback.msgSuccess('保存成功')
}

onMounted(async () => {
    await queryConfigs()
})
</script>
